<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChSmartTag;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;

class ChSmartTagMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChSmartTag::class;
    }

    /**
     * 根据用户ID和标签组ID获取标签列表.
     * @param mixed $uid
     * @param mixed $groupId
     * @return array
     */
//    #[Cacheable(prefix: 'ch_smart_tag_list',value: '#{id}_#{groupId}',ttl: 15 * 60)]
    public function getListByUidAndGroupId(mixed $uid,mixed $groupId): array
    {
        $list = $this->model::query()
            ->select(['id','name','parent_id'])
            ->where('uid',$uid)
            ->where('group_id',$groupId)
            ->get()->toArray();
        return $list;
    }

    /**
     * 根据标签ID获取标签信息
     * @param mixed $id
     * @return ChSmartTag|Model|string|Builder|null
     */
    public function findById(mixed $id): ChSmartTag|Model|string|Builder|null
    {
        return $this->model::query()->where('id',$id)->first();
    }

    /**
     * 检查标签名称是否已存在
     * @param string $name
     * @param mixed $id
     * @return bool
     */
    public function checkExistByName(string $name,mixed $parentId = null,mixed $id = null): bool
    {
        return $this->model::query()
            ->when(filled($id),function ($query) use ($id){
                $query->where('id','<>',$id);
            })
            ->when(filled($parentId),function ($query) use ($id,$parentId){
                $query->where('parent_id',$parentId);
            })
            ->where('name',$name)
            ->exists();
    }

    /**
     * 根据模块获取标签数量
     * @param mixed $mainUid
     * @param mixed $module
     * @param mixed|null $parentId
     * @return int
     */
    public function getCountByModule(mixed $mainUid,mixed $module,mixed $parentId = null): int
    {
        return $this->model::query()
            ->where('main_uid',$mainUid)
            ->where('module',$module)
            ->when(filled($parentId),function ($query) use ($parentId){
                $query->where('parent_id',$parentId);
            })
            ->count();
    }

    /**
     * 更新标签联系人数量
     * @param array $tagIds
     * @param int $contactCnt
     * @return void
     */
    public function updateContactCnt(array $tagIds,int $contactCnt): void
    {
        $query = $this->model::query()
            ->whereIn('id',$tagIds);
        if($contactCnt > 0){
            $query->increment('contact_cnt',$contactCnt);
        }else{
            $query->decrement('contact_cnt',abs($contactCnt));
        }
    }
}